package com.example.jsontoexcel.service;

import com.example.jsontoexcel.model.CashDetail;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

@Service
public class ExcelService {
    
    public byte[] exportToExcel(List<CashDetail> cashDetails) throws IOException {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("现金明细");
            
            // 创建标题行
            Row headerRow = sheet.createRow(0);
            String[] columns = {"银行编号", "开始日期", "设备类型", "设备ID", "冠字号码", "现金类型", 
                              "现金面值", "批次号", "现金版本", "数量", "图片名称", "交易信息",
                              "交易类型", "箱号"};
            
            CellStyle headerStyle = workbook.createCellStyle();
            headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);
            
            for (int i = 0; i < columns.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(columns[i]);
                cell.setCellStyle(headerStyle);
                sheet.setColumnWidth(i, 15 * 256); // 设置列宽
            }
            
            // 填充数据
            int rowNum = 1;
            for (CashDetail detail : cashDetails) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(detail.getBankNo());
                row.createCell(1).setCellValue(detail.getStartDate());
                row.createCell(2).setCellValue(detail.getDevType());
                row.createCell(3).setCellValue(detail.getDevId());
                row.createCell(4).setCellValue(detail.getGzh());
                row.createCell(5).setCellValue(detail.getCashType());
                row.createCell(6).setCellValue(detail.getCashValue());
                row.createCell(7).setCellValue(detail.getBatchNo());
                row.createCell(8).setCellValue(detail.getCashVer());
                row.createCell(9).setCellValue(detail.getQuality());
                row.createCell(10).setCellValue(detail.getImgName());
                row.createCell(11).setCellValue(detail.getTrInfo());
                row.createCell(12).setCellValue(detail.getTrType());
                row.createCell(13).setCellValue(detail.getBoxMon());
            }
            
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            return outputStream.toByteArray();
        }
    }
} 